class Solution {
    public int maxScore(int[] cardPoints, int k) {
        int len = cardPoints.length;
        int[] pre = new int[len + 1];
        pre[0] = 0;
        for (int i = 0; i < len; i++) {
            pre[i + 1] = cardPoints[i] + pre[i];
        }
        int max = -1;
        for (int i = 0; i <= k; i++) {
            max = Math.max(max, pre[i] + pre[len] - pre[len - k + i]);
        }
        return max;
    }
}